package com.taotao.tools.validate.utils;


import com.taotao.tools.core.bean.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

public class ValidatorUtils {


    /**
     * 校验对象所有字段是否合规
     *
     * @param obj
     * @param <T>
     */
    public static <T> void validateObj(T obj) {
        validateObj(obj, Default.class);
    }


    /**
     * 校验对象所有字段是否合规
     *
     * @param obj
     * @param groups
     * @param <T>
     */
    public static <T> void validateObj(T obj, Class<?>... groups) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> validateSet = validator.validate(obj, groups);
        if (!CollectionUtils.isEmpty(validateSet)) {
            for (ConstraintViolation<T> constraintViolation : validateSet) {
                throw new IllegalArgumentException(constraintViolation.getMessage());
            }
        }
    }


    /**
     * 校验某个字段
     *
     * @param object
     * @param propertyName
     * @param <T>
     */
    public static <T> void validateProperty(T object, String propertyName) {
        validateProperty(object, propertyName, Default.class);
    }


    /**
     * 校验某个字段
     *
     * @param object
     * @param propertyName
     * @param groups
     * @param <T>
     */
    public static <T> void validateProperty(T object,
                                            String propertyName,
                                            Class<?>... groups) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> validateSet = validator.validateProperty(object, propertyName, groups);
        if (!CollectionUtils.isEmpty(validateSet)) {
            for (ConstraintViolation<T> constraintViolation : validateSet) {
                throw new IllegalArgumentException(constraintViolation.getMessage());
            }
        }
    }


}
